package com.jdk.demo.nio.bilibili.Maodun.net.qiujuer3.lesson.sample.foo.handle;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.channels.SocketChannel;

import com.jdk.demo.nio.bilibili.Maodun.net.qiujuer3.lesson.sample.foo.Foo;
import com.jdk.demo.nio.bilibili.Maodun.net.qiujuer3.library.clink.box.StringReceivePacket;
import com.jdk.demo.nio.bilibili.Maodun.net.qiujuer3.library.clink.core.Connector;
import com.jdk.demo.nio.bilibili.Maodun.net.qiujuer3.library.clink.core.IoContext;
import com.jdk.demo.nio.bilibili.Maodun.net.qiujuer3.library.clink.core.Packet;
import com.jdk.demo.nio.bilibili.Maodun.net.qiujuer3.library.clink.core.ReceivePacket;
import com.jdk.demo.nio.bilibili.Maodun.net.qiujuer3.library.clink.utils.CloseUtils;

public class ConnectorHandler extends Connector {
	private final File cachePath;
    private final String clientInfo;
    private final ConnectorCloseChain closeChain = new DefaultPrintConnectorCloseChain();
    private final ConnectorStringPacketChain stringPacketChain = new DefaultNonConnectorStringPacketChain();

    public ConnectorHandler(SocketChannel socketChannel, File cachePath) throws IOException {
        this.clientInfo = socketChannel.getRemoteAddress().toString();
        this.cachePath = cachePath;

        System.out.println("新客户端连接：" + clientInfo);

        setup(socketChannel);
    }

    public String getClientInfo() {
		return clientInfo;
	}

    /**
     * 外部调用的退出操作
     */
    public void exit() {
        CloseUtils.close(this);
    }

    /**
     * 内部监测到链接断开的回调
     *
     * @param channel SocketChannel
     */
    @Override
    public void onChannelClosed(SocketChannel channel) {
        super.onChannelClosed(channel);
        closeChain.handle(this, this);
    }

    @Override
    protected File createNewReceiveFile(long length, byte[] headerInfo) {
        return Foo.createRandomTemp(cachePath);
    }

    @Override
    protected OutputStream createNewReceiveDirectOutputStream(long length, byte[] headerInfo) {
        // 服务器默认创建一个内存存储ByteArrayOutputStream
        return new ByteArrayOutputStream();
    }

    @Override
	protected void onReceivedPacket(ReceivePacket packet) {
        super.onReceivedPacket(packet);
        switch (packet.type()) {
			case Packet.TYPE_MEMORY_STRING: {
				deliveryStringPacket((StringReceivePacket)packet);
				break;
			}
			default: {
				System.out.println("New PAcket:" + packet.type() + "-" + packet.length());
			}
		}
    }

    private void deliveryStringPacket(StringReceivePacket packet) {
    	IoContext.get().getScheduler().delivery(() -> stringPacketChain.handle(this, packet));
	}

	public ConnectorStringPacketChain getStringPacketChain() {
		return stringPacketChain;
	}

	public ConnectorCloseChain getCloseChain() {
		return closeChain;
	}

}
